<style>
.pure_table_extra { width: 100%; margin-top: 5px; }
.pure_table_extra th { height: 25px; line-height: 25px; cursor: pointer; }
.pure_table_extra img { cursor: pointer; margin-right: 2px; }
.pure_table_extra td { vertical-align: middle; }
.pure-button-back { color: #666 !important; background: #eee !important; }
.pure-button-green { color: #fff !important; background: rgb(28, 184, 65) !important; }
.pure-button-red { color: #fff !important; background: rgb(255, 0, 0) !important; }
</style>

<?php 
$id = Utils::get_param('id', 0);
$start = Utils::get_param('start', date('Y-m-d', strtotime('last monday', strtotime('tomorrow'))));
$end = date('Y-m-d', strtotime($start) + (86400 * 4));

$data = new stdClass();

$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data->myclass = $orm->get('pb_colg_class', NULL, NULL, NULL, NULL, $opts)->d[0];
$data->myclass->__times = array();
$rslt = json_decode($data->myclass->times);
foreach ($rslt as $itm) {
  if ($data->myclass->type == PT_LANGUAGE) {
    $tmp = explode('-', $itm);
    $data->myclass->__times[] = array('MON ' . $tmp[0], date('Y-m-d ', strtotime($start)) . $tmp[0] . ':00');
    $data->myclass->__times[] = array('TUE ' . $tmp[0], date('Y-m-d ', strtotime($start) + (86400 * 1)) . $tmp[0] . ':00');
    $data->myclass->__times[] = array('WED ' . $tmp[0], date('Y-m-d ', strtotime($start) + (86400 * 2)) . $tmp[0] . ':00');
    $data->myclass->__times[] = array('THU ' . $tmp[0], date('Y-m-d ', strtotime($start) + (86400 * 3)) . $tmp[0] . ':00');
    $data->myclass->__times[] = array('FRI ' . $tmp[0], date('Y-m-d ', strtotime($start) + (86400 * 4)) . $tmp[0] . ':00');
  } else {
    $tmp = explode('#', $itm);
    $tmp2 = explode(' ', $tmp[0]);
    $tmp3 = date('Y-m-d', strtotime('Next ' . date('D', strtotime($tmp[0])), strtotime($start) - 86400));
    $data->myclass->__times[] = array(date('D', strtotime($tmp[0])) . ' ' . $tmp2[1], $tmp3 . ' ' . $tmp2[1] . ':00');
  }
}

$opts = new stdClass();
$opts->cd = 't.class_id = :v1 AND t.start = :v2';
$opts->cdv = array(':v1' => $id, ':v2' => $start);
$rslt = $orm->get('pb_colg_atdnlog', NULL, NULL, NULL, NULL, $opts)->d;
if (count($rslt) > 0) {
  $data->logged = 1;
  $data->logtime = $rslt[0]->add_at;
} else {
  $data->logged = 0;
  $data->logtime = '';
}

$opts = new stdClass();
$opts->cd = 't.class_id = :v1 AND (t2.start <= :v2 AND t2.end >= :v2) AND t.status != 3';
$opts->cdv = array(':v1' => $id, ':v2' => $start);
$opts->sel = 't.*, t1.id_number AS __id_number, t1.first_name AS __first_name, t1.last_name AS __last_name, t1.preferred_name AS __preferred_name, t1.citizenship AS __citizenship';
$opts->jt = 'LEFT JOIN pb_colg_student AS t1 ON t1.id = t.student_id LEFT JOIN pb_colg_enrolled_intake AS t2 ON t2.id = t.enrolled_intake_id';
$data->students = $orm->get('pb_colg_enrolled_class', 't1.id_number', 'ASC', NULL, NULL, $opts)->d;
foreach ($data->students as $itm) {
  $itm->__start = date('d/m/Y', strtotime($itm->start));
  $itm->__end = date('d/m/Y', strtotime($itm->end));
}

if ($data->logged == 1) {
  $opts = new stdClass();
  $opts->cd = 't.class_id = :v1 AND t.signin_at >= :v2 AND t.signin_at <= :v3';
  $opts->cdv = array(':v1' => $id, ':v2' => $start . ' 00:00:00', ':v3' => $end . ' 23:59:59');
  $data->atdn = $orm->get('pb_colg_atdn', NULL, NULL, NULL, NULL, $opts)->d;
  foreach ($data->atdn as $itm) {
    $itm->__signin_at = date('D H:i', strtotime($itm->signin_at));
  }
} else {
  $data->atdn = array();
  foreach ($data->students as $itm) {
    foreach ($data->myclass->__times as $itm2) {
      $obj = new stdClass();
      $obj->student_id = $itm->student_id;
      $obj->class_id = $id;
      $obj->enrolled_program_id = $itm->enrolled_program_id;
      $obj->enrolled_intake_id = $itm->enrolled_intake_id;
      $obj->enrolled_class_id = $itm->id;
      $obj->signin_at = $itm2[1];
      $obj->status = 0;
      $obj->is_absent = 0;
      $obj->is_tutorial = 0;
      $obj->__signin_at = $itm2[0];
      $data->atdn[] = $obj;
    }
  }
}

$opts = new stdClass();
$opts->cd = '(t1.start <= :v1 AND t1.end >= :v1) OR t.type = :v2 OR t.type = :v3';
$opts->cdv = array(':v1' => $start, ':v2' => PT_LANGUAGE, ':v3' => PT_NCEA_ENGLISH);
$opts->sel = 't.*, t1.start AS __start, t1.end AS __end, t2.id AS __logged';
$opts->jt = 'LEFT JOIN pb_colg_intake AS t1 ON t1.id = t.intake_id LEFT JOIN pb_colg_atdnlog AS t2 ON t2.class_id = t.id AND t2.start = \'' . $start . '\'';
$opts->gb = 't.id';
$objs = $orm->get('pb_colg_class', 't.name', 'ASC', 1, 9999, $opts);
foreach ($objs->d as $itm) {
  $itm->__title = (($itm->__logged) ? '* ' : ' ') . trim($itm->course_name . ' ' . $itm->name);
}

?>
<button class="pure-button pure-button-back" onclick="go_back();"><i class="fa fa-arrow-circle-left"></i>&nbsp;Back</button>
<button id="lognow" class="pure-button pure-primary" onclick="submit_atdn();">Save Now</button>
<button id="logtime" class="pure-button pure-primary pure-button-green"></button>
<button id="nolog" class="pure-button pure-primary pure-button-red">Not Saved Yet</button>
<div>&nbsp;</div>
<div class="pure-form">
  <legend><b id="myclass" style="font-size: 14px !important;"></b></legend>
  <table class="pure-table pure_table_extra" cellpadding=0 cellspacing=0>
    <thead id="class_head">
      <tr>
        <th style="width: 60px;" class="ui-widget-header">ID</th>
        <th style="width: 80px;" class="ui-widget-header">First</th>
        <th style="width: 80px;" class="ui-widget-header">Last</th>
        <th style="width: 80px;" class="ui-widget-header">English Name</th>
        <th style="width: 80px;" class="ui-widget-header">Nationality</th>
        <th style="width: 60px;" class="ui-widget-header">Start</th>
        <th style="width: 60px;" class="ui-widget-header">End</th>
      </tr>
    </thead>
    <tbody id="class_body"></tbody>
  </table>
</div>
<div>&nbsp;</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __class_id = '<?php echo $id; ?>';
  var __start = '<?php echo $start; ?>';
  var __end = '<?php echo $end; ?>';
  var __language = '<?php echo PT_LANGUAGE; ?>';
  var __pt_ncea_english = '<?php echo PT_NCEA_ENGLISH; ?>';
  
  $(function() {
    render();
  });
  
  function render() {
    Utils.leftbar(
      __objs,
      __class_id,
      __start + ' to ' + __end,
      '__title',
      function(page) {
      }
    );
    render_data();
  };
  
  function render_data() {
    if (__data.logged == 1) {
      $('#lognow').hide();
      $('#logtime').show();
      $('#logtime').html('Saved at ' + __data.logtime);
      $('#nolog').hide();
    } else {
      $('#lognow').show();
      $('#logtime').hide();
      $('#nolog').show();
    }
    
    Url.insert_param('id', __class_id);
    Url.insert_param('start', __start);

    $('#myclass').html(__data.myclass.course_name + ' ' + __data.myclass.name + ' (' + __start + ' to ' + __end + ')');
    
    $('#class_head th.head').remove();
    for (var idx in __data.myclass.__times) {
      var itm = __data.myclass.__times[idx];
      $('#class_head tr').append('<th class="head">' + itm[0] + '</th>');
    }

    $('#class_body').empty();
    for (var idx in __data.students) {
      var itm = __data.students[idx];
      $('#class_body').append(
        '<tr id="atdn_' + itm.id + '" class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td>' + itm.__id_number + ((itm.type_ncea__ != '') ? ' (N)' : '') + '</td>' +
          '<td title="' + itm.__first_name + '">' + Utils.get_short(itm.__first_name, 8) + '</td>' +
          '<td title="' + itm.__last_name + '">' + Utils.get_short(itm.__last_name, 8) + '</td>' +
          '<td title="' + itm.__preferred_name + '">' + Utils.get_short(itm.__preferred_name, 8) + '</td>' +
          '<td title="' + itm.__citizenship + '">' +  Utils.get_short(itm.__citizenship, 8) + '</td>' +
          '<td>' + itm.__start + '</td>' +
          '<td>' + itm.__end + '</td>' +
        '</tr>'
      );
      for (var idx2 in __data.myclass.__times) {
        var itm2 = __data.myclass.__times[idx2]; 
        var u = Utils.unique();
        $('#atdn_' + itm.id).append(
          '<td>' +
            '<select id="' + u + '" style="width: 60px; height: 20px; padding: 0;" onchange="change_atdn(' + itm.student_id + ', \'' + itm2[1] + '\', \'' + u + '\')">' +
              '<option value="0" title="Present">P</option>' +
              '<option value="1" title="Sick">S</option>' +
              '<option value="2" title="Holiday">H</option>' +
              '<option value="3" title="Absent">A</option>' +
              '<option value="4" title="Late">L</option>' +
              '<option value="5" title="Excused Absent">E</option>' +
              '<option value="-1" title="N/A">N/A</option>' +
            '</select>' +
          '</td>'
        );
        var rslt = get_atdn(itm.student_id, itm2[1]);
        if (rslt) {
          $('#' + u).val(rslt.status);
          if (rslt.status == 0) {
            $('#' + u).css('color', '#000');
          } else if (rslt.status == 1) {
            $('#' + u).css('color', '#0099FF');
          } else if (rslt.status == 2) {
            $('#' + u).css('color', '#33CC33');
          } else if (rslt.status == 3) {
            $('#' + u).css('color', '#ff0000');
          } else if (rslt.status == 4) {
            $('#' + u).css('color', '#FF6633');
          } else if (rslt.status == 5) {
            $('#' + u).css('color', '#FF0099');
          } else if (rslt.status == -1) {
            $('#' + u).css('color', '#A0A0A0');
          }
        } else {
          $('#' + u).css('border', '1px solid #ff0000');
        }
      }
    }
    if (__data.students.length == 0) {
      $('#class_body').append('<tr class="pure-table-even"><td colspan=' + $('#class_head tr').children('th').length + '>None</td></tr>');
    }
  };

  function go_back() {
    Url.redirect(__redmd, __sys + '.php?i=' + __id + '&start=' + __start);
  };

  function get_atdn(student_id, signin_at) {
    for (var idx in __data.atdn) {
      var itm = __data.atdn[idx];
      if (itm.student_id == student_id && itm.signin_at == signin_at) {
        return itm;
      }
    }
    return null;
  };

  function change_atdn(student_id, signin_at, u) {
    for (var idx in __data.atdn) {
      var itm = __data.atdn[idx];
      if (itm.student_id == student_id && itm.signin_at == signin_at) {
        itm.status = $('#' + u + ' :selected').val();
        itm.is_absent = (itm.status == 3) ? 1 : 0;
        
        if (itm.id) {
          var req = {
            log: 0,
            atdn: [ itm ]
          };
          Ajax.request(
            __requrl + 'submit_atdn',
            'req=' + Utils.encodeURI(JSON.stringify(req)),
            function(rslt) {
              
            },
            null
          );
        }
      }
    }
    render_data();
  };

  function submit_atdn() {
    var req = {
      log: 1,
      start: __start,
      class_id: __class_id,
      atdn: __data.atdn
    };
    Ajax.request(
      __requrl + 'submit_atdn',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data.atdn = rslt;
        __data.logged = 1;
        __data.logtime = 'Now';
        for (var idx in __objs.d) {
          var itm = __objs.d[idx];
          if (itm.id == __data.myclass.id) {
            if (itm.__title.indexOf('* ') == -1) {
              itm.__title = '* ' + itm.__title;
            }
          }
        }
        render();
      },
      null
    );
  };
  
  function get_obj(id) {
    Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=' + __file + '&start=' + __start + '&id=' + id);
  };
  /*]]>*/
</script>